package com.hsmpay.mobile.util;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import sun.misc.BASE64Decoder;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.channels.FileChannel;
import java.util.Random;
//import com.sun.image.codec.jpeg.JPEGCodec;
//import com.sun.image.codec.jpeg.JPEGImageEncoder;

public class ImgFileUpload {
    public static final String WATER_IMG_NAME = "/images/watermark/shuiyin_";
    public static final String extendFile = ".png";
    private static final String TEXT_TITLE = "北京中亿支付科技发展有限公司！！！";
    private static Logger log = Logger.getLogger(ImgFileUpload.class);

    public static boolean delFile(File myDelFile) {
        boolean del = false;
        if (myDelFile != null) {
            if (!myDelFile.isDirectory()) {    //如果文件不是目录
                if (!myDelFile.exists()) {    //如果文件不存在
                    del = false;
                } else {
                    del = myDelFile.delete();    //文件存在，删除，返回true
                }
            }
        }
        return del;
    }

    /**
     * 上传文件
     *
     * @param newFileName 新文件名称，包括路径
     * @param uploadFile  上传的文件
     * @return newFileName
     */
    public static void upload(String newFileName, File uploadFile, Long terminalTypeId) {
        FileOutputStream fos = null;
        FileInputStream fis = null;
        try {
            //给原图 添加水印
            String extentionName = getFileType(uploadFile.toString());
            Image src = ImageIO.read(uploadFile);
            if (src != null && !extentionName.toLowerCase().equals(".gif")) {
                //非动态图片 添加水印
//		       imageWaterMark(uploadFile,0.2f,terminalTypeId);   去除水印
                //watermark(imageFile);
            }
            fos = new FileOutputStream(newFileName);
            fis = new FileInputStream(uploadFile);
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = fis.read(buffer)) > 0) {
                fos.write(buffer, 0, len);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fis != null) try {
                fis.close();
            } catch (Exception e) {
            }
            if (fos != null) try {
                fos.close();
            } catch (Exception e) {
            }
        }
//		return newFileName;
    }

    /**
     * 上传文件
     *
     * @param newFileName 新文件名称，包括路径
     * @param fileStream  上传的文件流
     * @return newFileName
     */
    public static void uploadFile(String newFileName, File uploadFile) {
        FileOutputStream fos = null;
        FileInputStream fis = null;
        try {
            fos = new FileOutputStream(newFileName);
            fis = new FileInputStream(uploadFile);
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = fis.read(buffer)) > 0) {
                fos.write(buffer, 0, len);
            }
            fis.close();
            fos.close();
            /*int data = fis.read();
            while(data != -1){
				fos.write(data);
			}
			fis.close();
			fos.close();*/
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fis != null) try {
                fis.close();
            } catch (Exception e) {
            }
            if (fos != null) try {
                fos.close();
            } catch (Exception e) {
            }
        }
//		return newFileName;
    }

    /**
     * 上传文件  该方法上传的缩略图  路径就是数据库保存路径的图片路径 扩展名后加_thumb
     *
     * @param newFileName 新文件名称，包括路径
     * @param uploadFile  上传的文件
     * @return newFileName
     */
    public static void uploadAndThumd(String newFileName, File uploadFile, int wi, int he, Long terminalTypeId) throws Exception {
        try {
            // 缩略图存放路径
            String outdir = newFileName.substring(0, newFileName.lastIndexOf(File.separator));
            File todir = new File(outdir);
            if (!todir.exists()) {
                todir.mkdir();
            }

            File imageFile = new File(newFileName);
            //1 生成原图 原尺寸保存 用于点击放大使用
            copyFile(uploadFile, imageFile, terminalTypeId);

            String extentionName = getFileType(newFileName);
            StringBuilder sb = new StringBuilder();
            String thumbPath = sb.append(newFileName.substring(0, newFileName.lastIndexOf("."))).append("_thumb").append(extentionName).toString();

            Image src = ImageIO.read(imageFile);
            int[] thumbWebwh = getNewWH(src, wi, he);
		        
		    /*if(!extentionName.toLowerCase().equals(".gif")){
		        //非动态图片 添加水印
		       imageWaterMark(imageFile,0.2f);   
		    	//watermark(imageFile);
		    }*/
            zoom(imageFile, thumbWebwh[0], thumbWebwh[1], thumbPath);
        } catch (IOException e) {
            e.printStackTrace();
            throw e;
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

    public static void copyFile(File src, File dest, Long terminalTypeId) {
        FileChannel in = null;
        FileChannel out = null;
        FileInputStream fis = null;
        FileOutputStream fos = null;
        try {
            //给原图 添加水印
            String extentionName = getFileType(src.toString());
            if (!extentionName.toLowerCase().equals(".gif")) {
                //非动态图片 添加水印
//		       imageWaterMark(src,0.2f,terminalTypeId);   
                //watermark(imageFile);
            }

            fis = new FileInputStream(src);
            fos = new FileOutputStream(dest);
            in = fis.getChannel();
            out = fos.getChannel();

            in.transferTo(0, in.size(), out);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (in != null) try {
                in.close();
            } catch (Exception e) {
            }
            if (out != null) try {
                out.close();
            } catch (Exception e) {
            }
            if (fis != null) try {
                fis.close();
            } catch (Exception e) {
            }
            if (fos != null) try {
                fos.close();
            } catch (Exception e) {
            }
        }
    }

    /**
     * 根据路径创建一系列的目录
     *
     * @param path
     */
    public static String mkDirectory(String path) {
        File file = null;
        try {
            file = new File(path);
            if (!file.exists()) {
                file.mkdirs();
            }
        } catch (RuntimeException e) {
            e.printStackTrace();
        }

        return file.getPath();
    }

    /**
     * 判断文件是否存在
     *
     * @param fileName
     * @param dir
     * @return
     */
    public static boolean isFileExist(String fileName, String dir) {
        File files = new File(dir + fileName);
        return (files.exists()) ? true : false;
    }

    /**
     * 获得随机文件名,保证在同一个文件夹下不同名
     *
     * @param fileName
     * @param dir
     * @return
     */
    public static String getRandomName(String fileName, String dir) {
        String[] split = fileName.split("\\.");// 将文件名已.的形式拆分
        String extendFile = "." + split[split.length - 1].toLowerCase(); // 获文件的有效后缀

        Random random = new Random();
        int add = random.nextInt(1000000); // 产生随机数10000以内
        String ret = add + extendFile;
        while (isFileExist(ret, dir)) {
            add = random.nextInt(1000000);
            ret = fileName + add + extendFile;
        }
        return ret;
    }

    /**
     * 获取文件的后缀名称
     *
     * @param fileName 文件所在的url
     * @return
     */
    public static String getFileType(String fileName) {
        String[] split = fileName.split("\\.");// 将文件名已.的形式拆分
        String extendFile = "." + split[split.length - 1].toLowerCase(); // 获文件的有效后缀
        return extendFile;
    }

    /**
     * 获取文件的后缀名称
     *
     * @param fileName 文件所在的url
     * @return
     */
    public static String getFileTypeName(String fileName) {
        String[] split = fileName.split("\\.");// 将文件名已.的形式拆分
        String extendFile = split[split.length - 1].toLowerCase(); // 获文件的有效后缀
        return extendFile;
    }

    /**
     * 缩放处理
     *
     * @return
     */
    public static void zoom(File imageFile, int wi, int he, String newName) throws Exception {
        try {
            if (!imageFile.isFile()) {
                throw new Exception(imageFile + " is not image file error in CreateThumbnail!");
            }

            File sImg = new File(newName);
            BufferedImage bi = ImageIO.read(imageFile);
            // 假设图片宽 高 最大为130 80,使用默认缩略算法   
            Image Itemp = bi.getScaledInstance(wi, he, Image.SCALE_SMOOTH);

            BufferedImage bImage = new BufferedImage(Itemp.getWidth(null), Itemp.getHeight(null), BufferedImage.TYPE_INT_RGB);
            bImage.getGraphics().drawImage(Itemp, 0, 0, null);
            ImageIO.write(bImage, "jpeg", sImg);

        } catch (IOException e) {
            e.printStackTrace();
            throw new Exception(e);
        }
    }

    /**
     * 添 加文字水印
     *
     * @return
     * @throws Exception
     * @throws Exception
     */
    public static void watermark(File img) throws Exception {
        //log.debug("[watermark file name]--" + img.getPath());   
        try {
            if (!img.exists()) {
                throw new IllegalArgumentException("file not found!");
            }
            //log.debug("[watermark][img]--" + img);   

            // 创建一个FileInputStream对象从源图片获取数据流   
            FileInputStream sFile = new FileInputStream(img);

            // 创建一个Image对象并以源图片数据流填充   
            Image src = ImageIO.read(sFile);
            // 得到源图宽   
            int width = src.getWidth(null);
            // 得到源图长   
            int height = src.getHeight(null);

            // 创建一个BufferedImage来作为图像操作容器   
            BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            // 创建一个绘图环境来进行绘制图象   
            Graphics2D g = image.createGraphics();
            // 将原图像数据流载入这个BufferedImage   
            //log.debug("width:" + width + " height:" + height);   
            g.drawImage(src, 0, 0, width, height, null);
            // 设定文本字体   
            g.setFont(new Font("宋体", Font.BOLD, 28));
            String rand = TEXT_TITLE;
            // 设定文本颜色   
            g.setColor(Color.red);
            // 设置透明度   
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 0.9f));
            // 向BufferedImage写入文本字符,水印在图片上的坐标   
            //g.drawString(rand, width - (width - 20), height - (height - 60));   
            g.drawString(rand, width / 11, height / 11); // 添加水印的文字和设置水印文字出现的内容
            // 使更改生效   
            g.dispose();
            // 创建输出文件流   
            FileOutputStream outi = new FileOutputStream(img);
            // 创建JPEG编码对象   
            // JPEGImageEncoder encodera = JPEGCodec.createJPEGEncoder(outi);
            // 对这个BufferedImage (image)进行JPEG编码
            // encodera.encode(image);
            // 关闭输出文件流
            ImageIO.write(image, "jpeg", outi);
            outi.close();
            sFile.close();

        } catch (IOException e) {
            e.printStackTrace();
            throw new Exception(e);
        }
    }

    /**
     * 添加图片水印
     */
    public static void imageWaterMark(File imgFile, float opacity, Long terminalTypeId) throws Exception {
        try {
            if (null == terminalTypeId) {
                return;
            }
            // 目标文件   
            Image src = ImageIO.read(imgFile);
            int wideth = src.getWidth(null);
            int height = src.getHeight(null);
            BufferedImage image = new BufferedImage(wideth, height, BufferedImage.TYPE_INT_RGB);
            Graphics2D g = image.createGraphics();
            g.drawImage(src, 0, 0, wideth, height, null);

            String waterImgName = WATER_IMG_NAME + terminalTypeId + extendFile;
            // 水印文件 路径   
            String waterImgPath = ServletActionContext.getServletContext().getRealPath(waterImgName);
            File waterFile = new File(waterImgPath);
            Image waterImg = ImageIO.read(waterFile);

            int w_wideth = waterImg.getWidth(null);
            int w_height = waterImg.getHeight(null);
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, opacity));
            g.drawImage(waterImg, (wideth - w_wideth) / 1, (height - w_height) / 1, w_wideth, w_height, null);
            // 水印文件结束   

            g.dispose();
            FileOutputStream out = new FileOutputStream(imgFile);
            // JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
            // encoder.encode(image);
            ImageIO.write(image, "jpeg", out);
            out.close();

            //File imgFile1 = new File("D:\\watermark\\","c.jpg");
            //ImageIO.write(image, "jpeg", imgFile1);  
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 为等比缩放计算输出的图片宽度及高度
     *
     * @param img
     * @param outputWidth
     * @param outputHeight
     * @return
     */
    public static int[] getNewWH(Image img, int outputWidth, int outputHeight) {

        int w = img.getWidth(null);
        int h = img.getHeight(null);
        int temp;
        int[] wh = new int[2];
        if (w > outputWidth) {
            temp = outputWidth;
        } else {
            temp = w;
        }
        if ((h * temp / w) > outputHeight) {
            int height = outputHeight;
            int width = (int) (outputHeight / (h + 0.0) * w);
            wh[0] = width;
            wh[1] = height;
        } else {
            int width = temp;
            int height = (int) ((temp + 0.0) / w * h);
            wh[0] = width;
            wh[1] = height;
        }
        return wh;

    }

    /**
     * 测试返回的 签名图片
     *
     * @param fileRelPath
     * @param picBuffer
     */
    public static File getPicByBase64Str(String fileRelPath, String picBuffer) {
        File file = null;
        File fileTemp = null;
        if (StringUtils.isBlank(picBuffer)) {
            return file;
        }
        try {
            byte[] picByte = new BASE64Decoder().decodeBuffer(picBuffer);
            String tempPath = fileRelPath.substring(0, fileRelPath.lastIndexOf(File.separator))+File.separator;
            String filename = fileRelPath.substring(fileRelPath.lastIndexOf(File.separator));
            file = new File(tempPath);
            if (!file.exists()) {
                file.mkdirs();
            }
            fileTemp = new File(file,filename);
            if(!fileTemp.exists()){
                fileTemp.createNewFile();
            }
            FileOutputStream out = new FileOutputStream(fileTemp);
            out.write(picByte);
            out.flush();
            out.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
        return fileTemp;
    }

    /**
     * 根据Base64Str 上传文件
     *
     * @param filePath
     * @param fileBase64Str
     */
    public static void uploadFileBase64Str(String filePath, String fileBase64Str) {
        try {
            byte[] picByte = new BASE64Decoder().decodeBuffer(fileBase64Str);
            File file = new File(filePath);
            FileOutputStream out = new FileOutputStream(file);
            out.write(picByte);
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public static void main(String args[]) {
        String str = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDavTXnRYKwowo6UyjtXmN+29mwjBDwLxwy4McGUJYqba+g88ThlznhDB9rBesZjTka0evRSmRM3Cfbxqmr50jghr/NNBWp+9GKokixheUsbVptklXQhZP7tMhAj+6ZoIh7PR4RZafdzYcgxezYog1ouW5zhcbAHIbwPqkFXzTWpwIDAQAB";
        String str1 = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDavTXnRYKwowo6UyjtXmN+29mwjBDwLxwy4McGUJYqba+g88ThlznhDB9rBesZjTka0evRSmRM3Cfbxqmr50jghr/NNBWp+9GKokixheUsbVptklXQhZP7tMhAj+6ZoIh7PR4RZafdzYcgxezYog1ouW5zhcbAHIbwPqkFXzTWpwIDAQAB";

        log.debug(str.equals(str1));
    }
}
